package com.anuprayog.treasureloot;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;


/**
 * @author amit
 * Shows the bomb exploding with sound after the game ends
 */
public class ExplosionActivity extends Activity {

	// used to know if the back button was pressed in the splash screen activity and avoid opening the next activity
    private boolean mIsBackButtonPressed;
    private static final int SPLASH_DURATION = 2000; // 2 seconds
 
    public static String HIGH_SCORE = "com.anuprayog.treasureloot.SCORE";
	public static String SOUND_OFF_STRING = "com.anuprayog.treasureloot.SOUND";
	public String scor;
	public String soundStat;
	
	public int OLD_HIGH_SCORE=0;
	
	public int NEW_HIGH_SCORE;
	
	 private String filename = "MyFile1.txt";
	 private String filepath = "MyFileStorage1";
	 File myInternalFile1;
	
	/**
	 * Reference to the ImageView which will display the animation.
	 */
	ImageView animation;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // requesting to turn the title OFF
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // making it full screen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.activity_explosion);
 
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        
        //code added by manoj chand on 23 july 2013
		ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
		File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
		myInternalFile1 = new File(directory , filename);
        
        animation = (ImageView)findViewById(R.id.imageAnimation);
        
        animation.setBackgroundResource(R.drawable.animation);		// the frame-by-frame animation defined as a xml file within the drawable folder
        
        /*
         * NOTE: It's not possible to start the animation during the onCreate.
         */
        
        Handler handler = new Handler();
        
        Intent i = getIntent();
		
		scor = i.getStringExtra(MainGamePanel.HIGH_SCORE);
		
		soundStat = i.getStringExtra(MainGamePanel.SOUND_OFF_STRING);
 
		MediaPlayer explosion = MediaPlayer.create(ExplosionActivity.this, R.raw.explosion);
    	
		if (soundStat.equals("false")){
    		explosion.start();
		}
    	
        // run a thread after 2 seconds to start the home screen
        handler.postDelayed(new Runnable() {
 
            @Override
            public void run() {
 
                // make sure we close the splash screen so the user won't come back when it presses back key
 
                finish();
                 
                if (!mIsBackButtonPressed) {
                    // start the home screen if the back button wasn't pressed already
                    Intent intent = new Intent(ExplosionActivity.this, GameOverActivity.class);
                    intent.putExtra(HIGH_SCORE, scor);
        			intent.putExtra(SOUND_OFF_STRING, soundStat);
        			ExplosionActivity.this.startActivity(intent);
               }
                 
            }
 
        }, SPLASH_DURATION); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
 
      //call to get high score
		OLD_HIGH_SCORE = getHighScore();
		
		try {
			NEW_HIGH_SCORE = Integer.parseInt(scor);
		} catch (RuntimeException e){
			NEW_HIGH_SCORE = 0;
		}
		
		if (NEW_HIGH_SCORE > OLD_HIGH_SCORE){
			OLD_HIGH_SCORE = NEW_HIGH_SCORE;
		}
		
		//call to set high score
		setHighScore(OLD_HIGH_SCORE);
		
	}
	
	//function created by manoj chand to set high score in internal storage
	public void setHighScore(int score){
		try {
			String strScore = score+"";
		    FileOutputStream fos = new FileOutputStream(myInternalFile1);
		    fos.write(strScore.getBytes());
		    fos.close();
		   } catch (IOException e) {
		    e.printStackTrace();
		   }
	}

	//function created by manoj chand to get high score from internal storage
	public int getHighScore(){
		String myData="0";
		   try {
			    FileInputStream fis = new FileInputStream(myInternalFile1);
			    DataInputStream in = new DataInputStream(fis);
			    BufferedReader br = new BufferedReader(new InputStreamReader(in));
			    String strLine;
			    while ((strLine = br.readLine()) != null) {
			     myData = strLine;
			    }
			    in.close();
			   } catch (IOException e) {
			    e.printStackTrace();
			   }
		   if(myData != null && myData.trim().equals(""))
			   myData="0";
		   return Integer.parseInt(myData);
		}
	
	@Override
    /**
     * This method is called whenever the Activity becomes visible or invisible to the user.
     * During this method call its possible to start the animation.
     */
	public void onWindowFocusChanged (boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		AnimationDrawable frameAnimation = 
			(AnimationDrawable) animation.getBackground();
		if(hasFocus) {
			frameAnimation.start();
		} else {
			frameAnimation.stop();
		}
	}
    
    @Override
    public void onBackPressed() {
  
         // set the flag to true so the next activity won't start up
         mIsBackButtonPressed = true;
         super.onBackPressed();
  
     }

}
